package com.gimi.cloud.bbp.manage.service.sys.impl;

import com.gimi.cloud.bbp.manage.service.sys.AuthService;
import com.gimi.cloud.bbp.manage.service.sys.MenuService;
import com.gimi.cloud.bbp.common.enums.ResponseCodeEnum;
import com.gimi.cloud.bbp.common.exception.MsgException;
import com.gimi.cloud.bbp.common.utils.NumberUtil;
import com.gimi.cloud.bbp.common.utils.StringUtil;
import com.gimi.cloud.bbp.dao.dao.sys.SysAuthorityDao;
import com.gimi.cloud.bbp.dto.sys.SysAuthorityDTO;
import com.gimi.cloud.bbp.dto.sys.SysMenuDTO;
import com.gimi.cloud.bbp.dto.params.AuthListParams;
import com.gimi.cloud.bbp.dto.params.DoAuthParams;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by shazhiwei on 2017/12/18.
 */
@Service
public class AuthServiceImpl implements AuthService {
    private final SysAuthorityDao authDao;
    private final MenuService menuService;

    public AuthServiceImpl(SysAuthorityDao authDao, MenuService menuService){
        this.authDao = authDao;
        this.menuService = menuService;
    }

    @Override
    public List<Map<String,Object>> getAuthList(AuthListParams params) {
        List<Map<String,Object>> result = null;
        SysMenuDTO menuDTO = new SysMenuDTO();
        menuDTO.setMePid(params.getMenuId());
        List<SysMenuDTO> menuList = menuService.getMenuListByPid(menuDTO);
        if(menuList != null && menuList.size() > 0){
            result = initState(params.getRoleId(),menuList);
        }
        return result;
    }

    @Override
    public List<SysMenuDTO> getAuthTree(AuthListParams params) {
        List<SysMenuDTO> allList = menuService.getMenuList();
        //allList = dataFilter(allList);
        List<SysMenuDTO> authList = menuService.getMenuListByRoleId(params.getRoleId());
        return menuService.getMenuTree(allList,authList);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = {Exception.class})
    public void doAuth(DoAuthParams params) throws MsgException {
        String roleId = params.getRoleId();
        String menuIds = params.getMenuIds();
        if(StringUtil.isBlank(roleId) || StringUtil.isBlank(menuIds)){
            throw new MsgException(ResponseCodeEnum.MANAGE_AUTH_DO_AUTH_ERR);
        }
        //删除该角色权限
        authDao.deleteByRoleId(NumberUtil.getInt(roleId));
        //重新授权
        String sql = "INSERT INTO sys_authority(ro_id,me_id,au_created) VALUES ";
        String values = getValues(roleId,menuIds);
        if(!StringUtil.isBlank(values)){
            sql = sql + values;
            authDao.saveBatch(sql);
        }else{
            throw new MsgException(ResponseCodeEnum.ERR_PASSWORD_TO_GET_TOKEN);
        }
    }

    /**
     * 拼凑batchSave values
     * @param roleId 角色id
     * @param menuIds 菜单id,如：1,2,3
     * @return
     */
    private String getValues(String roleId,String menuIds){
        String[] meIds = menuIds.split(",");
        StringBuilder sb = new StringBuilder();
        if(meIds != null && meIds.length > 1){
            for(int i = 0;i<meIds.length;i++){
                sb.append("(");
                sb.append(NumberUtil.getInt(roleId)).append(",").append(meIds[i]).append(",").append("now()");
                sb.append("),");
            }
            if(sb.length() > 0){
                sb.delete(sb.length()-1,sb.length());
            }
        }
        return sb.toString();
    }

    List<SysMenuDTO> dataFilter(List<SysMenuDTO> allList){
        List<SysMenuDTO> result = null;
        if(allList != null && allList.size() > 0){
            result = new ArrayList<>();
            for (SysMenuDTO dto : allList){
                SysMenuDTO tmp = new SysMenuDTO();
                tmp.setMeId(dto.getMeId());
                tmp.setMePid(dto.getMePid());
                tmp.setMeName(dto.getMeName());
                tmp.setMeAlias(dto.getMeAlias());
                tmp.setMeIcon(dto.getMeIcon());
                result.add(tmp);
            }
        }
        return result;
    }

    List<Map<String,Object>> initState(Integer roleId,List<SysMenuDTO> list){
        List<Map<String,Object>> result = null;
        if(list != null && list.size() > 0){
            List<SysAuthorityDTO> data = authDao.getListByRoleId(roleId);
            if(data != null && data.size() > 0){
                Map<Integer,Integer> meIdMap = new HashMap<>();
                for(int i = 0;i<data.size();i++){
                    SysAuthorityDTO tmp = data.get(i);
                    meIdMap.put(tmp.getMeId(),i);
                }
                result = new ArrayList<>();
                for (SysMenuDTO dto : list){
                    Map<String,Object> tmpMap = new HashMap<>();
                    tmpMap.put("meId",dto.getMeId());
                    tmpMap.put("name",dto.getMeName());
                    tmpMap.put("alias",dto.getMeAlias());
                    Integer state = meIdMap.containsKey(dto.getMeId()) ? 1 : 0;//是否打钩
                    tmpMap.put("state",state);
                    result.add(tmpMap);
                }
            }
        }
        return result;
    }


}
